package com.sora.sys.service.impl;

import com.sora.basic.service.impl.BaseServiceImpl;
import com.sora.sys.domain.Menu;
import com.sora.sys.mapper.MenuMapper;
import com.sora.sys.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;
    
    @Override
    public List<Menu> getMenuTree() {
        List<Menu> menus = menuMapper.loadAll();

        Map<Long, Menu> map = new HashMap<>();

        for (Menu menu : menus) {
            map.put(menu.getId(),menu);
        }

        ArrayList<Menu> menuTree = new ArrayList<>();
        for (Menu menu : menus) {
            if(menu.getParentId() == null){
                menuTree.add(menu);
            }else{
                Long parentId = menu.getParentId();
                Menu parentMenu = map.get(parentId);
                if(parentMenu != null){
                    parentMenu.getChildren().add(menu);
                }
            }
        }

        return menuTree;
    }

}
